package com.yann.bomb.crud;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.yann.bomb.BaseActivity;
import com.yann.bomb.R;
import com.yann.bomb.crud.bean.Category;
import com.yann.bomb.util.LogUtils;
import com.yann.bomb.util.StringUtils;
import com.yann.bomb.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by yayun.xia on 2018/11/27
 */
public class UpdateActivity extends BaseActivity implements View.OnClickListener {

    private EditText edtId;
    private EditText edtName;
    private Button btnUpdate, btnUpdateBatch;
    private String mObjectId;
    private String nameStr;

    @Override
    public int intiLayout() {
        return R.layout.activity_update;
    }

    @Override
    public void initView() {
        setTitle("更新Bomb测试");

        edtId = findView(R.id.edt_id);
        edtId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mObjectId = s.toString();
                changeBtnStatus();
            }
        });
        edtName = findView(R.id.edt_name);
        edtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                nameStr = s.toString();
                changeBtnStatus();
            }
        });
        btnUpdate = findView(R.id.btn_update);
        btnUpdateBatch = findView(R.id.btn_batch_update);
        btnUpdate.setOnClickListener(this);
        btnUpdateBatch.setOnClickListener(this);

    }

    private void changeBtnStatus() {
        if (StringUtils.isEmpty(nameStr) || StringUtils.isEmpty(mObjectId)) {
            btnUpdate.setEnabled(false);
            btnUpdateBatch.setEnabled(false);
        } else {
            btnUpdate.setEnabled(true);
            btnUpdateBatch.setEnabled(true);
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_update:
                update();
                break;
            case R.id.btn_batch_update:
                updateBatch();
                break;
            default:
                break;
        }
    }

    private void update() {
        Category category = new Category();
        category.setSequence(getObjectIds().length);
        category.setName(getNames()[0]);
        category.update(getObjectIds()[0], new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ToastUtils.showLong("更新成功");
                } else {
                    LogUtils.e("BMOB", e.getMessage());
                    ToastUtils.showLong(e.getMessage());
                }
            }
        });
    }

    private void updateBatch() {
        if (!isNames2IDs()) {
            ToastUtils.showLong("ObjectId应该和name属性保持数目一致");
            return;
        }

        List<BmobObject> categories = new ArrayList<>();

        for (int i = 0; i < getNames().length; i++) {
            Category category = new Category();
            category.setObjectId(getObjectIds()[i]);
            category.setName(getNames()[i]);
            category.setDesc("类别" + System.currentTimeMillis());
            categories.add(category);
        }


        new BmobBatch().updateBatch(categories).doBatch(new QueryListListener<BatchResult>() {
            @Override
            public void done(List<BatchResult> results, BmobException e) {
                if (e == null) {
                    for (int i = 0; i < results.size(); i++) {
                        BatchResult result = results.get(i);
                        BmobException ex = result.getError();
                        if (ex == null) {
                            LogUtils.e("第" + i + "个数据批量更新成功：" + result.getCreatedAt() + "," + result.getObjectId() + "," + result.getUpdatedAt());
                        } else {
                            LogUtils.e("第" + i + "个数据批量更新失败：" + ex.getMessage() + "," + ex.getErrorCode());
                        }
                    }
                    ToastUtils.showLong("更新成功");
                } else {
                    LogUtils.e("失败：" + e.getMessage() + "," + e.getErrorCode());
                    ToastUtils.showLong("失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    public String[] getObjectIds() {
        String[] ObjectIds = mObjectId.split(",");
        for (int i = 0; i < ObjectIds.length; i++) {
            LogUtils.d("更新ObjectIds:" + ObjectIds[i]);
        }
        return ObjectIds;
    }

    public String[] getNames() {
        String[] names = nameStr.split(",");
        for (int i = 0; i < names.length; i++) {
            LogUtils.d("更新name:" + names[i]);
        }
        return names;
    }

    private boolean isNames2IDs() {
        return getNames().length == getObjectIds().length;
    }
}
